const router = require("koa-router")();
const uuid = require("uuid/v1");
/**
 *
 * api {get} /home/app/plugins/imgcode/page/:page 获取图片验证码列表
 *
 */
router.get("/imgcode/page/:page", async (ctx, nex) => {
  const page = ctx.params.page;
  const baas = ctx.baas;
  const list = await BaaS.Models.plugins_imgcode
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
    })
    .fetchPage({
      pageSize: ctx.config.pageSize,
      page: page,
      withRelated: []
    });

  ctx.success(list);
});
/**
 * api {get} /home/app/plugins/imgcode/id/:id 获取图片验证码
 *
 */
router.get("/imgcode/id/:id", async (ctx, nex) => {
  const id = ctx.params.id;
  const baas = ctx.baas;
  const imgcode = await BaaS.Models.plugins_imgcode
    .query(qb => {
      qb.where("id", "=", id);
      qb.where("baas_id", "=", baas.id);
    })
    .fetch();

  ctx.success(imgcode);
});
/**
 * api {post} /home/app/plugins/imgcode/add 图片验证
 *
 * apiParam {Number} length 应用id
 * apiParam {String} exclude 字符排除
 * apiParam {Number} line 干扰线条数
 * apiParam {Number} color 字符是否有颜色
 * apiParam {String} bgcolor 背景颜色
 *
 */
router.post("/imgcode/add", async (ctx, nex) => {
  const { id, length = 4, exclude = "", line = 2, color, bgcolor } = ctx.post;
  const baas = ctx.baas;
  const key = `length:${length}:exclude:${exclude}:line:${line}:color${color}:bgcolor:${bgcolor}`;
  // 验证表单是否为空
  const isEmpty = ctx.isEmpty({ length: length, color: color }, [
    "length",
    "color"
  ]);
  if (!isEmpty) {
    ctx.error("请完善表单");
    return;
  }
  const locked = await BaaS.redis.lock(key);
  if (locked) {
    const data = {
      id: id,
      baas_id: baas.id,
      code: uuid(),
      length: length,
      exclude: exclude,
      line: line,
      color: color,
      bgcolor: bgcolor
    };
    if (id) {
      delete data.code;
    }
    const result = await BaaS.Models.plugins_imgcode.forge(data).save();
    ctx.success(result);

    await BaaS.redis.unlock(key);
  } else {
    ctx.error("系统繁忙，请稍后重试");
    console.log(`${key} Waiting`);
    return;
  }
});
/**
 * api {get} /home/app/plugins/imgcode/del/:id 获取图片验证码
 *
 */
router.get("/imgcode/del/:id", async (ctx, nex) => {
  const id = ctx.params.id;
  const baas = ctx.baas;
  const imgcode = await BaaS.Models.plugins_imgcode
    .forge({ id: id, baas_id: baas.id })
    .destroy();

  ctx.success(imgcode);
});

module.exports = router;
